
package com.carsite.webapp.action;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.carsite.Constants;
import com.carsite.model.Branch;
import com.carsite.model.Department;
import com.carsite.model.Role;
import com.carsite.model.User;
import com.carsite.service.BranchManager;
import com.carsite.service.DepartmentManager;
import com.carsite.webapp.form.DepartmentForm;

/**
 * Action class to handle CRUD on a Department object
 *
 * @struts.action name="departmentForm" path="/departments" scope="request"
 *  validate="false" parameter="method" input="mainMenu"
 * @struts.action name="departmentForm" path="/editDepartment" scope="request"
 *  validate="false" parameter="method" input="list"
 * @struts.action name="departmentForm" path="/saveDepartment" scope="request"
 *  validate="true" parameter="method" input="edit"
 * @struts.action-set-property property="cancellable" value="true"
 * @struts.action-forward name="edit" path="/WEB-INF/pages/departmentForm.jsp"
 * @struts.action-forward name="list" path="/WEB-INF/pages/departmentList.jsp"
 * @struts.action-forward name="search" path="/departments.html" redirect="true"
 */
public final class DepartmentAction extends BaseAction {
    public ActionForward cancel(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception {
        return mapping.findForward("search");
    }

    public ActionForward delete(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Entering 'delete' method");
        }
        if(!this.check(request)){
        	return null;
        }
        ActionMessages messages = new ActionMessages();
        DepartmentForm departmentForm = (DepartmentForm) form;

        // Exceptions are caught by ActionExceptionHandler
        DepartmentManager mgr = (DepartmentManager) getBean("departmentManager");
        mgr.removeDepartment(departmentForm.getDeptId());

        messages.add(ActionMessages.GLOBAL_MESSAGE,
                     new ActionMessage("department.deleted"));

        // save messages in session, so they'll survive the redirect
        saveMessages(request.getSession(), messages);
        
        departmentForm = new DepartmentForm();
        updateFormBean(mapping, request, departmentForm);
        
        BranchManager branchMgr = (BranchManager) getBean("branchManager");
        List topBranchList = branchMgr.getTopBranchs();
        request.setAttribute(Constants.BRANCH_LIST,topBranchList);

        return mapping.findForward("edit");
        
        
    }

    public ActionForward edit(ActionMapping mapping, ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Entering 'edit' method");
        }
        if(!this.check(request)){
        	return null;
        }
        DepartmentForm departmentForm = (DepartmentForm) form;
         
        
        BranchManager branchMgr = (BranchManager) getBean("branchManager");
        
        if (departmentForm.getDeptId() != null) {
            DepartmentManager mgr = (DepartmentManager) getBean("departmentManager");
            Department department = mgr.getDepartment(departmentForm.getDeptId());
            departmentForm = (DepartmentForm) convert(department);
            if(department.getBranch() != null){
            	departmentForm.setBranchId(department.getBranch().getBranchId().toString());
            	departmentForm.setBranchName(department.getBranch().getBranchName());
            	
            }
            
            updateFormBean(mapping, request, departmentForm);
        }else{
        	
 	
        	 if(departmentForm.getBranchId()!=null &&!departmentForm.getBranchId().equals("")){
        		 
        		 Branch branch = branchMgr.getBranch(departmentForm.getBranchId());
        		 departmentForm.setBranchId(branch.getBranchId().toString());
             	 departmentForm.setBranchName(branch.getBranchName());
             }
        	 
         
        }
        
       
        List topBranchList = branchMgr.getTopBranchs();
        request.setAttribute(Constants.BRANCH_LIST,topBranchList);

        
        return mapping.findForward("edit");
    }

    public ActionForward save(ActionMapping mapping, ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Entering 'save' method");
        }
        if(!this.check(request)){
        	return null;
        }
        // Extract attributes and parameters we will need
        ActionMessages messages = new ActionMessages();
        DepartmentForm departmentForm = (DepartmentForm) form;
        boolean isNew = ("".equals(departmentForm.getDeptId()) || departmentForm.getDeptId() == null);

        DepartmentManager mgr = (DepartmentManager) getBean("departmentManager");
        //Department department =mgr.getDepartment(departmentForm.getDeptId());
        Department department= (Department) convert(departmentForm);
        
        BranchManager branchMgr = (BranchManager) getBean("branchManager");
        
        if(departmentForm.getBranchId()!=null &&!departmentForm.getBranchId().equals("")){
        	Branch branch = branchMgr.getBranch(departmentForm.getBranchId());
        	department.setBranch(branch);
        }
        
        //mgr.removeDepartment(department.getDeptId()+"");
        mgr.saveDepartment(department);

        // add success messages
        if (isNew) {
            messages.add(ActionMessages.GLOBAL_MESSAGE,
                         new ActionMessage("department.added"));

            // save messages in session to survive a redirect
            saveMessages(request.getSession(), messages);

           
        } else {
            messages.add(ActionMessages.GLOBAL_MESSAGE,
                         new ActionMessage("department.updated"));
            saveMessages(request, messages);

           
        }
       
        
        departmentForm = new DepartmentForm();
        updateFormBean(mapping, request, departmentForm);
        
        List topBranchList = branchMgr.getTopBranchs();
        request.setAttribute(Constants.BRANCH_LIST,topBranchList);
           
        return mapping.findForward("edit");
        
    }

    public ActionForward search(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Entering 'search' method");
        }

        DepartmentForm departmentForm = (DepartmentForm) form;
        Department department = (Department) convert(departmentForm);

        DepartmentManager mgr = (DepartmentManager) getBean("departmentManager");
   //     request.setAttribute(Constants.DEPARTMENT_LIST, mgr.getDepartments(department));

        return mapping.findForward("list");
    }
    public ActionForward unspecified(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request,
                                     HttpServletResponse response)
            throws Exception {
        return search(mapping, form, request, response);
    }
    public boolean check(HttpServletRequest request){
		 HttpSession session=request.getSession();
		 if(session==null){
			 return false;
		 }else{
			 User currentUser=(User)session.getAttribute("currentUser");
			 if(currentUser==null){
				 return false;
			 }else{
				 Set roles=currentUser.getRoles();
				 Iterator rolesIt=(Iterator)roles.iterator();
				 while(rolesIt.hasNext()){
					 
					 Role role=(Role)rolesIt.next();
					 if(role.getName().equals("admin")){
						 return true;
					 }
				 }
				 return false;
			 }
		 }
		
	 }

}
